export default {
    // 获取光标位置
    getCursortPosition (textDom) {
        var cursorPos = 0
        if (document.selection) {
            // IE Support
            textDom.focus()
            var selectRange = document.selection.createRange()
            selectRange.moveStart('character', -textDom.value.length)
            cursorPos = selectRange.text.length
        } else if (textDom.selectionStart || textDom.selectionStart == '0') {
            // Firefox support
            cursorPos = textDom.selectionStart
        }
        return cursorPos
    },
    // 设置光标位置
    setCaretPosition(textDom, pos) {
        if (textDom.setSelectionRange) {
            // IE Support
            textDom.focus()
            textDom.setSelectionRange(pos, pos)
        } else if (textDom.createTextRange) {
            // Firefox support
            var range = textDom.createTextRange()
            range.collapse(true)
            range.moveEnd('character', pos)
            range.moveStart('character', pos)
            range.select()
        }
    },
    // 获取选中文字
    getSelectText() {
        var userSelection, text
        if (window.getSelection) {
            // Firefox support
            userSelection = window.getSelection()
        } else if (document.selection) {
            // IE Support
            userSelection = document.selection.createRange()
        }
        if (!(text = userSelection.text)) {
            text = userSelection
        }
        return text.toString()
    },
    /**
     * 选中特定范围的文本
     * 参数：
     *     textDom  [JavaScript DOM String] 当前对象
     *     startPos  [Int]  起始位置
     *     endPos  [Int]  终点位置
     *     selectionDirection 选择方向 有"forward","backward"和"none" 3个可选值
     */
    setSelectText(textDom, startPos, endPos, selectionDirection) {
        var startPos = parseInt(startPos),
            endPos = parseInt(endPos),
            textLength = textDom.value.length;
        if (textLength) {
            if (!startPos) {
                startPos = 0
            }
            if (!endPos) {
                endPos = textLength
            }
            if (startPos > textLength) {
                startPos = textLength
            }
            if (endPos > textLength) {
                endPos = textLength
            }
            if (startPos < 0) {
                startPos = textLength + startPos
            }
            if (endPos < 0) {
                endPos = textLength + endPos
            }
            if (textDom.createTextRange) {
                // IE Support
                var range = textDom.createTextRange()
                range.moveStart('character', -textLength)
                range.moveEnd('character', -textLength)
                range.moveStart('character', startPos)
                range.moveEnd('character', endPos)
                range.select()
            } else {
                // Firefox support
                if (selectionDirection) {
                    textDom.setSelectionRange(startPos, endPos, 'backward')
                } else {
                    textDom.setSelectionRange(startPos, endPos)
                }

                textDom.focus()
            }
        }
    },
    /**
     * 在光标后插入文本
     * 参数：
     *     textDom  [JavaScript DOM String] 当前对象
     *     value  [String]  要插入的文本
     */
    insertAfterText(textDom, value) {
        var selectRange
        if (document.selection) {
            // IE Support
            textDom.focus()
            selectRange = document.selection.createRange()
            selectRange.text = value
            textDom.focus()
        } else if (textDom.selectionStart || textDom.selectionStart == '0') {
            // Firefox support
            var startPos = textDom.selectionStart
            var endPos = textDom.selectionEnd
            var scrollTop = textDom.scrollTop
            textDom.value = textDom.value.substring(0, startPos) + value + textDom.value.substring(endPos, textDom.value.length)
            textDom.focus()
            textDom.selectionStart = startPos + value.length
            textDom.selectionEnd = startPos + value.length
            textDom.scrollTop = scrollTop
        } else {
            textDom.value += value
            textDom.focus()
        }
    },
    // base64转为Blob
    dataURLtoBlob(dataurl) {
        var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
            bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n)
        while (n--) {
            u8arr[n] = bstr.charCodeAt(n)
        }
        return new Blob([u8arr], { type: mime })
    },
    // Blob转为base64
    blobToDataURL(blob, callback) {
        let a = new FileReader()
        a.onload = function (e) { callback(e.target.result) }
        a.readAsDataURL(blob)
    },
    // 将base64转换为文件
    dataURLtoFile(dataurl, filename) {
        var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
            bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n)
        while(n--) {
            u8arr[n] = bstr.charCodeAt(n)
        }
        return new File([u8arr], filename,{ type: mime })
    },
    // 将图片转换为Base64
    getImgToBase64(url, callback) {
        var canvas = document.createElement('canvas'),
            ctx = canvas.getContext('2d'),
            img = new Image()
        img.crossOrigin = 'Anonymous'
        img.onload = function() {
            canvas.height = img.height
            canvas.width = img.width
            ctx.drawImage(img, 0, 0)
            var dataURL = canvas.toDataURL('image/png')
            callback(dataURL)
            canvas = null
        }
        img.src = url
    },
    dataLetterSort(list) {
        // 转换 格式 进行 排序
        if (!list) return
        let resault = []
        for (let key in list) {
            resault.push({
                letter: key,
                list: list[key]
            })
        }
        resault.sort(function (x, y) {
            return x.letter.charCodeAt(0) - y.letter.charCodeAt(0)
        })
        // # 号分组 放最后
        let lastArr = resault[0]
        resault.splice(0, 1)
        resault.push(lastArr)

        // 转换 数据 格式
        let jsonSort = {}
        for (let j = 0; j < resault.length; j++) {
            jsonSort[resault[j].letter] = resault[j].list
        }

        return jsonSort
    },

    // 返回聊天列表索引
    chartListFilter(id, array) {
        let index = -1
        for (let i = 0; i < array.length; i++) {
            if (array[i].id == parseInt(id)) {
                index = i
            }
        }
        return index
    },

    // 通过消息id获取消息
    chartCurrMsgByMsgId(msgId, array) {
        let obj = {
            index: -1,
            msgObj: {}
        }
        for (let i = 0; i < array.length; i++) {
            let arrs = array[i].msgData.filter(el => { return el.msgId == msgId })
            if (arrs.length > 0) {
                obj.msgObj = arrs[0]
                obj.index = i
            }
        }
        return obj
    },

    // 时间戳可视化
    dateFormat(timestamp, format) {
        if (!format) {
            format = 'yyyy-MM-dd hh:mm:ss'
        }
        timestamp = parseInt(timestamp)
        let realDate = new Date(timestamp)
        function timeFormat(num) {
            return num < 10 ? '0' + num : num
        }
        let date = [
            ['M+', timeFormat(realDate.getMonth() + 1)],
            ['d+', timeFormat(realDate.getDate())],
            ['h+', timeFormat(realDate.getHours())],
            ['m+', timeFormat(realDate.getMinutes())],
            ['s+', timeFormat(realDate.getSeconds())],
            ['q+', Math.floor((realDate.getMonth() + 3) / 3)],
            ['S+', realDate.getMilliseconds()]
        ]

        let regYear = new RegExp('(y+)', 'i')
        let reg1 = regYear.exec(format)
        if (reg1) {
            format = format.replace(reg1[1], (realDate.getFullYear() + '').substring(4 - reg1[1].length))
        }
        for (let i = 0; i < date.length; i++) {
            let k = date[i][0]
            let v = date[i][1]

            let reg2 = new RegExp('(' + k + ')').exec(format)
            if (reg2) {
                format = format.replace(reg2[1], reg2[1].length == 1
                    ? v : ('00' + v).substring(('' + v).length))
            }
        }
        return format
    },

    // 获取当前时间戳
    getTimestamp() {
        return new Date().getTime()
    },

    // 在光标处插入文本
    insertAtCursor(myField, myValue) {
        let value = myField.value
        // IE support
        if (document.selection) {
            myField.focus()
            sel = document.selection.createRange()
            sel.text = myValue
            sel.select()
        } else if (myField.selectionStart || myField.selectionStart == '0') {
            var startPos = myField.selectionStart
            var endPos = myField.selectionEnd
            // save scrollTop before insert
            var restoreTop = myField.scrollTop
            value = value.substring(0, startPos) + myValue + value.substring(endPos, value.length)
            if (restoreTop > 0) {
                // restore previous scrollTop
                myField.scrollTop = restoreTop
            }
            myField.focus()
            myField.selectionStart = startPos + myValue.length
            myField.selectionEnd = startPos + myValue.length
        } else {
            value += myValue
            myField.focus()
        }
        return value
    },

    replaceURLToLink(text) {
        const strRegex = /((((https?|ftp?):(?:\/\/)?)(?:[-;:&=\+\$]+@)?[A-Za-z0-9.-]+|(?:(www.)?|[-;:&=\+\$]+@)[A-Za-z0-9.-]+)(\.com|\.cn|\.me|\.net|\.org|\.info|\.co|\.tv|\.pro|\.im|\.top)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\?\+=&;:%!\/@.\w_]*)#?(?:[-\+=&;%!\?\/@.\w_]*))?)/gi
        text = text.replace(strRegex, function (a) {
            if (arguments[7]) {
                if (arguments[7].startsWith('#') || arguments[7].startsWith('/') || arguments[7].startsWith('?')) {
                    if (a.startsWith('http://') || a.startsWith('https://') || a.startsWith('ftp://')) {
                        return '<a target="_blank" href="' + a + '">' + a + '</a>'
                    } else {
                        return '<a target="_blank" href="//' + a + '">' + a + '</a>'
                    }
                } else {
                    if (a.startsWith('http://') || a.startsWith('https://') || a.startsWith('ftp://')) {
                        return '<a target="_blank" href="' + arguments[2] + arguments[6] + '">' + arguments[2] + arguments[6] + '</a>' + arguments[7]
                    } else {
                        return '<a target="_blank" href="//' + arguments[2] + arguments[6] + '">' + arguments[2] + arguments[6] + '</a>' + arguments[7]
                    }
                }
            } else {
                if (a.startsWith('http://') || a.startsWith('https://') || a.startsWith('ftp://')) {
                    return '<a target="_blank" href="' + a + '">' + a + '</a>'
                } else {
                    return '<a target="_blank" href="//' + a + '">' + a + '</a>'
                }
            }
        })
        return text
    }
}
